package com.ultrapower.ultracsa.product.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import com.ultrapower.ultracsa.product.service.IPService;

@Controller
public class IPConfigController {

	private static final String FILE_NAME = "ipTemplate.xls";
	private static final String PATH = IPConfigController.class
			.getClassLoader().getResource("/").getPath();
	private static final int DEFAULTROW = 20;
	@Resource
	private IPService ipService;

	@RequestMapping(value = "ipConfig")
	public String getIPConfig(Map<String, Object> model) {

		return "deploy/ip_config";
	}

	/**
	 * ajax 获取所有的Ip数据
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "getIpData", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getIpData(@RequestBody Map<String, String> map) {
		int currentPage = Integer.parseInt(map.get("currentPage"));
		String ip_search = map.get("ip_search");
		Map<String, Object> map1 = ipService.IPList(ip_search,currentPage, DEFAULTROW);

		return map1;

	}


	/**
	 * 批量删除ip
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "deleteIps", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteIps(@RequestBody Map<String, String> map) {

		Map<String, Object> resultMap = ipService.batchDeleteIps(map);
		return resultMap;
	}

	/**
	 * 新增ip
	 * 
	 * @param map
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "insertIp", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> insertIp(@RequestBody Map<String, String> map,
			HttpSession session,HttpServletRequest request) {
		RequestContext requestContext = new RequestContext(request);
		String user = (String) session.getAttribute("userName");
		map.put("user", user);
		Map<String, Object> resultMap = ipService.insertIP(map, requestContext);
		return resultMap;

	}

	/**
	 * 修改Ip信息
	 * 
	 * @param map
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "updateIp", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateIp(@RequestBody Map<String, String> map,
			HttpSession session,HttpServletRequest request) {
		RequestContext requestContext = new RequestContext(request);
		String userIp = getRequestIp(request);
		String user = (String) session.getAttribute("userName");
		map.put("user", user);
		map.put("userIp", userIp);
		Map<String, Object> resultMap = ipService.updateIP(map,requestContext);
		return resultMap;
	}

	/**
	 * 下载IP模板
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "downLoadTemplateFile", params = "method=downLoadFile")
	public ModelAndView downLoadTemplateFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// String path =
		// this.getClass().getClassLoader().getResource("/").getPath();
		String filePath = PATH.split("classes")[0];
		filePath += "file" + File.separator + "template" + File.separator
				+ FILE_NAME;
		System.out.println(filePath);
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// String downLoadPath="rr.sql";
		long fileLength = new File(filePath).length();
		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(FILE_NAME.getBytes("utf-8"), "utf-8"));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		bis = new BufferedInputStream(new FileInputStream(filePath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
		return null;
	}

	/**
	 * 导入Ip excel
	 * 
	 * @param request
	 * @param session
	 * @return
	 * @throws IOException
	 */

	@RequestMapping(value = "importIp", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upLoadFile(
			@RequestParam("file") MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		RequestContext requestContext = new RequestContext(request);
		String userIp = getRequestIp(request);
		Map<String, Object> map = ipService.inserIPs(userIp,file,session,requestContext);
		return map;
	}
	
	/**
	 * 获取请求客户端IP,解决客户端多层代理获取不到真正IP的问题
	 * @param request
	 * @return
	 */
	private String getRequestIp(HttpServletRequest request){

		 String ip = request.getHeader("x-forwarded-for");
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("Proxy-Client-IP");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("WL-Proxy-Client-IP");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getRemoteAddr();
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("http_client_ip");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		 }
		 // 如果是多级代理，那么取第一个ip为客户ip
		 if (ip != null && ip.indexOf(",") != -1) {
		  ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		 }
		 return ip;
	}

}
